<template>
  <div class="app-container">
    <div class="contentBox">
      <div class="searchBox">
        <el-form :model="queryParams" ref="queryRef" :inline="true" @submit.prevent>
          <el-form-item prop="name" style="margin: 0 6px 0 0;">
            <el-input
                class="inputBox"
                v-model="queryParams.name"
                placeholder="请输入仓库名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item style="margin: 0 6px 0 0;">
            <el-button class="normalFormBg searchBtn" icon="Search" @click="handleQuery"></el-button>
            <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetQuery"></el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-row :gutter="10" style="margin: 16px 0;">
        <el-col :span="1.5">
          <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:stockManage:shelfManage:add']"
               @click="handleModalShow('新增仓库')">
            <img src="@/assets/images/plus.png" class="normalBtn_icon">
            <div class="normalBtn_text">新增</div>
          </div>
        </el-col>
      </el-row>
      <el-table
          v-loading="loading"
          :data="dataList"
          border>
        <el-table-column prop="id" label="仓库ID" width="200" :show-overflow-tooltip="true" fixed="left"></el-table-column>
        <el-table-column prop="warehouseNo" label="仓库编码" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
        <el-table-column prop="name" label="仓库名称" width="200" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="cover" label="仓库图片" width="80" align="center">
          <template #default="scope">
            <div class="tableImgBox1">
              <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)"
                        @click="handlePreviewShow(setCoverUrl(scope.row.cover))" v-if="scope.row.cover" />
              <div class="emptyBox" v-else>暂无图片</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="capacity" label="容量" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="仓库类别" width="150">
          <template #default="scope">
            <div v-for="(item, index) in gas_stock_storage_type" :key="index" v-show="item.value == scope.row.type">
              <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
              <div v-else>{{ item.label }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="存料类别" width="150">
          <template #default="scope">
            <div v-for="(item, index) in gas_stock_storage_good_type" :key="index" v-show="item.value == scope.row.storageType">
              <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
              <div v-else>{{ item.label }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="所属区域" width="200" :show-overflow-tooltip="true">
          <template #default="scope">
            <div>{{scope.row.province}}/{{scope.row.city}}/{{scope.row.district}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" width="200" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="isEnable" label="状态" width="70">
          <template #default="scope">
            <div v-for="(item, index) in system_open_status" :key="index" v-show="item.value == scope.row.isEnable">
              <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
              <div v-else>{{ item.label }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="340" align="center" fixed="right">
          <template #default="scope">
            <div class="pageFlex pageFlexCenter" style="width: 100%;">
              <div class="pageFlex pageFlexCenter btnSetBox" @click="handleInfo(scope.row.id)">
                <img src="@/assets/images/fileManage.png" class="img">
                <div class="text">详情</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:shelfManage:list']"
                   @click="toPage('/gasManage/stockManage/shelfManage?id='+scope.row.id)" v-if="scope.row.isEnable == 1">
                <img src="@/assets/images/fileManage.png" class="img">
                <div class="text">货架管理</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:shelfManage:edit']"
                   @click="handleEdit(scope.row.id)">
                <img src="@/assets/images/edit.png" class="img">
                <div class="text">修改</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:shelfManage:delete']"
                   @click="handleDelete(scope.row.id, scope.row.name)">
                <img src="@/assets/images/delete.png" class="img">
                <div class="text">删除</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据"/>
        </template>
      </el-table>
      <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
        <div class="totalText">共计 {{total}} 条</div>
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="queryParams.page" :page-size="queryParams.pageSize" @current-change="handleCurrentChange"/>
      </div>
    </div>
    <el-drawer v-model="modalShow" direction="rtl" size="600" :title="modalTitle">
      <div class="modalBox">
        <div class="modalBoxContent">
          <el-form
              ref="formRef"
              class="formContent"
              label-width="100"
              :model="form"
              :rules="rules"
              :disabled="modalTitle === '仓库详情'"
          >
            <div class="formContentTop pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">仓库信息</div>
            </div>
            <div class="formContentCenter bgFF">
              <el-form-item label="仓库图片" prop="cover">
                <div class="imgBox">
                  <ImageUpload ref="cover" v-model="form.cover" bg="#FFFFFF" v-if="modalShow"></ImageUpload>
                </div>
              </el-form-item>
              <el-form-item label="仓库名称" prop="name">
                <el-input
                    class="inputBox"
                    v-model="form.name"
                    placeholder="请输入仓库名称"
                    clearable
                />
              </el-form-item>
              <el-form-item label="仓库容量" prop="capacity">
                <el-input
                    class="inputBox"
                    type="number"
                    v-model="form.capacity"
                    placeholder="请输入仓库容量"
                    clearable
                />
              </el-form-item>
              <el-form-item label="仓库类别" prop="type">
                <el-select class="inputBox" v-model="form.type" placeholder="请选择仓库类别" clearable>
                  <el-option v-for="dict in gas_stock_storage_type" :key="dict.value" :label="dict.label"
                     :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="存料类别" prop="storageType">
                <el-select class="inputBox" v-model="form.storageType" placeholder="请选择存料类别" clearable>
                  <el-option v-for="dict in gas_stock_storage_good_type" :key="dict.value" :label="dict.label"
                             :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="所属区域" prop="location">
                <SelectOption class="selectOptionBox" ref="locationSelectOption" placeHolder="请选择所属区域" title="区域选择"
                    v-model="form.location" selectType="multi" maxSelectLength="3" treeNodeKey="name" :defaultFormValue="locationDefault"
                    :disabled="modalTitle === '仓库详情'"
                    @loadOptions="locationDataLoad" @chooseError="locationChooseError" @chooseConfirm="locationChooseConfirm" v-if="modalShow && !formLoading"/>
              </el-form-item>
              <el-form-item label="联系地址" prop="address">
                <el-input
                    class="inputBox"
                    v-model="form.address"
                    placeholder="请输入联系地址"
                    clearable
                />
              </el-form-item>
              <el-form-item label="仓库描述" prop="description">
                <el-input
                    class="textareaBox"
                    type="textarea"
                    v-model="form.description"
                    :rows="6"
                    placeholder="请输入仓库描述"
                    clearable
                />
              </el-form-item>
              <el-form-item label="是否为子仓库" prop="isSub">
                <el-radio-group v-model="form.isSub">
                  <el-radio
                      v-for="dict in sys_normal_disable"
                      :key="dict.value"
                      :value="dict.value"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态" prop="isEnable">
                <el-radio-group v-model="form.isEnable">
                  <el-radio
                      v-for="dict in system_open_status"
                      :key="dict.value"
                      :value="dict.value"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="lineBox" v-if="modalTitle !== '仓库详情'"></div>
        <div class="bottomBox pageFlex pageFlexCenter" v-if="modalTitle !== '仓库详情'">
          <el-button type="primary" :loading="submitLoading" @click="submitNow">确认提交</el-button>
        </div>
        <el-button type="primary" :loading="formLoading" class="modalLoadingBox" v-if="formLoading">加载数据中</el-button>
      </div>
    </el-drawer>
    <el-image-viewer :url-list="srcList" @close="handlePreviewClose" v-if="showPreview"/>
  </div>
</template>
<script setup>
import { computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { searchWarehouseApi, addWarehouseApi, searchWarehouseByIdApi, editWarehouseApi, deleteWarehouseApi } from '@/api/gasManage/stockManage/storageManage';
import ImageUpload from '@/views/gasManage/components/ImageUpload';
import SelectOption from '@/views/gasManage/components/SelectOption';
import {ElLoading, ElMessageBox} from "element-plus";
const { proxy } = getCurrentInstance();
const { sys_normal_disable, system_open_status, gas_stock_storage_type, gas_stock_storage_good_type } = proxy.useDict("sys_normal_disable", "system_open_status", "gas_stock_storage_type", 'gas_stock_storage_good_type');
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const router = useRouter();
// ---------------------------- 查询 ------------------------------------
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: ''
})
const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const showPreview = ref(false);
const srcList = ref([])
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
function handleQuery(){
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery(){
  proxy.resetForm("queryRef");
  handleQuery();
}
async function getList(){
  loading.value = true;
  let data = await shelfManageListApi(queryParams.value);
  if(data && Array.isArray(data)){
    dataList.value = data;
  }else{
    dataList.value = [];
  }
  loading.value = false;
}
function shelfManageListApi(params){
  return new Promise(resolve => {
    searchWarehouseApi(params).then(res => {
      total.value = Number(res.total);
      resolve(Array.isArray(res.rows) ? res.rows : []);
    }).catch(() => {resolve(false)})
  })
}
function handleCurrentChange(e){
  queryParams.value.pageNum = e;
  getList();
}
function handlePreviewShow(link){
  srcList.value = [link];
  showPreview.value = true;
}
function handlePreviewClose(){
  showPreview.value = false;
  srcList.value = [];
}
function toPage(link, row){
  let url = link;
  if(row){
    url += row.id
  }
  router.push(url);
}
//-----------------------------------所属区域选择------------------------
import { areasList } from '@/api/system/location';
const locationDefault = ref('');
async function locationDataLoad(e){
  const { node, resolve } = e;
  let id = node.level === 0 ? 0 : node.data.id;
  let data = [];
  if(node.data.isEnable != 0){
    if(node.level !== 3){
      data = await areasListApi({parentId: id});
    }
    if(data.length){
      data.map(item=>{
        item.checked = item.isEnable == 0;
        return item
      })
    }
  }
  proxy.$refs.locationSelectOption.handleLoadApi(data, node, resolve);
}
function locationChooseError(e){
  proxy.$modal.msgError('【所属区域】'+e.msg);
}
function locationChooseConfirm(e){
  e.keys.forEach((item, index)=>{
    if(index === 0){
      form.value.province = item;
    }else if(index === 1){
      form.value.city = item;
    }else{
      form.value.district = item;
    }
  })
}
function areasListApi(params){
  return new Promise(resolve=>{
    areasList(params).then(res=>{
      resolve(Array.isArray(res.data) ? res.data : []);
    }).catch(()=>{resolve([])})
  })
}
// ----------------------------弹窗-------------------------------
const modalShow = ref(false);
const modalTitle = ref('');
const formLoading = ref(false);
const submitLoading = ref(false);
const form = ref({
  cover: '',
  name: '',
  capacity: 0,
  type: '',
  storageType: '',
  location: '',
  address: '',
  description: '',
  isSub: '0',
  isEnable: '1',
  province: '',
  city: '',
  district: ''
})
const rules = ref({
  cover: [{ required: true, message: "仓库图片未上传", trigger: "blur" }],
  name: [{ required: true, message: "仓库名称不能为空", trigger: "blur" }],
  capacity: [{ required: true, message: "仓库容量不能为空", trigger: "blur" }],
  type: [{ required: true, message: "请选择仓库类别", trigger: "blur" }],
  storageType: [{ required: true, message: "请选择存料类型", trigger: "blur" }],
  location: [{ required: true, message: "请选择仓库所属区域", trigger: "blur" }],
  address: [{ required: true, message: "联系地址不能为空", trigger: "blur" }],
})
function handleModalShow(name){
  proxy.resetForm('formRef');
  locationDefault.value = '';
  modalTitle.value = name;
  modalShow.value = true;
}
function handleModalHide(){
  modalShow.value = false;
}
async function setFormData(id){
  formLoading.value = true;
  let data = await getShelfDataApi(id);
  if(data){
    data.isEnable = String(data.isEnable);
    data.type = String(data.type);
    data.storageType = String(data.storageType);
    form.value = data;
    locationDefault.value = form.value.province+'/'+form.value.city+'/'+form.value.district;
    form.value.location = [form.value.province, form.value.city, form.value.district]
  }else{
    handleModalHide();
  }
  formLoading.value = false;
}
function getShelfDataApi(id){
  return new Promise(resolve => {
    searchWarehouseByIdApi(id).then(res => {
      resolve(res.data);
    }).catch(()=>{
      resolve(false);
    })
  })
}
function submitNow(){
  if(submitLoading.value) return;
  proxy.$refs["formRef"].validate(valid => {
    if(valid){
      submitLoading.value = true;
      if(modalTitle.value === '新增仓库'){
        addNow();
      }else{
        editNow();
      }
    }else{
      proxy.$modal.alertWarning('有必填选项未填写，请查看！');
    }
  })
}
// ----------------------------详情-------------------------------
function handleInfo(id){
  handleModalShow('仓库详情');
  setFormData(id);
}
// ----------------------------修改-------------------------------
function handleEdit(id){
  handleModalShow('修改仓库信息');
  setFormData(id);
}
function editNow(){
  let params = JSON.parse(JSON.stringify(form.value));
  delete params.createBy;
  delete params.createTime;
  delete params.updateBy;
  delete params.updateTime;
  delete params.location;
  editWarehouseApi(params).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('修改仓库信息成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// ----------------------------新增-------------------------------
function addNow(){
  let params = JSON.parse(JSON.stringify(form.value));
  params.type = Number(params.type);
  params.storageType = Number(params.storageType);
  delete params.location;
  addWarehouseApi(params).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('新增仓库成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// ----------------------------删除-------------------------------
function handleDelete(id, name){
  ElMessageBox.confirm(`确认删除仓库名称为【${name}】的数据`,'提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteNow(id, name);
  }).catch(() => {})
}
async function deleteNow(id, name){
  const loading = ElLoading.service({
    lock: true,
    text: '删除中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  deleteWarehouseApi(id).then(()=>{
    loading.close();
    proxy.$modal.msgSuccess(name+'仓库删除成功');
    getList();
  }).catch(()=>{
    loading.close();
  })
}
onMounted(()=>{
  getList();
})
</script>
<style lang='scss' scoped>
@import "@/assets/styles/public.scss";
:deep(.el-input){
  .el-input__wrapper{
    background-color: $formBgSet;
    box-shadow: none;
  }
}
.app-container{
  width: 100%;
  min-height: calc(100vh - 66px);
  background: #F8F8F9;
  .contentBox{
    width: 100%;
    min-height: $pageMinHeight;
    background-color: #FFFFFF;
    border-radius: 5px;
    box-sizing: border-box;
    padding: 12px;
    .searchBtn{
      width: 32px;
      height: 32px;
      font-size: 12px;
      padding: 0;
      border: none;
      margin: 0 6px 0 0px;
    }
    .btnSetBox{
      padding: 0 10px;
      box-sizing: border-box;
      border-right: 1px solid $borderColor;
      cursor: pointer;
      .text{
        height: 16px;
        line-height: 16px;
        color: var(--el-color-primary);
      }
      .img{
        width: 16px;
        height: 16px;
        margin-right: 2px;
      }
      &:last-child{
        border-right: none;
      }
    }
    .totalText{
      height: 22px;
      font-weight: 400;
      font-size: 14px;
      color: #1D2129;
      line-height: 22px;
    }
  }
}
:deep(.el-drawer){
  .el-drawer__header{
    margin: 0;
    padding-bottom: 20px;
  }
  .el-drawer__body{
    padding: 0;
  }
}
</style>
